package com.holike.crm.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;

import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;


public class SystemTintHelper {
    private static final String TAG_STATUS_BAR = "TAG_STATUS_BAR";
//    /**
//     * 状态栏亮色模式，设置状态栏黑色文字、图标，
//     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
//     *
//     * @return 1:MIUUI 2:Flyme 3:android6.0
//     */
//    @SuppressWarnings("UnusedReturnValue")
//    public static int setStatusBarLightMode(Activity activity) {
//        return setStatusBarLightMode(activity.getWindow());
//    }
//
//    public static int setStatusBarLightMode(Window window) {
//        int result = 0;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                result = 3;
//            } else {
//                if (MIUISetStatusBarLightMode(window, true)) {
//                    result = 1;
//                } else if (flyMeSetStatusBarLightMode(window, true)) {
//                    result = 2;
//                }
//            }
//        }
//        return result;
//    }
//
//
//    /**
//     * 已知系统类型时，设置状态栏黑色文字、图标。
//     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
//     *
//     * @param type 1:MIUUI 2:Flyme 3:android6.0
//     */
//    @SuppressWarnings("unused")
//    public static void setStatusBarLightMode(Activity activity, int type) {
//        if (type == 1) {
//            MIUISetStatusBarLightMode(activity.getWindow(), true);
//        } else if (type == 2) {
//            flyMeSetStatusBarLightMode(activity.getWindow(), true);
//        } else if (type == 3) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//            }
//        }
//    }
//
//    /**
//     * 状态栏暗色模式，清除MIUI、flyme或6.0以上版本状态栏黑色文字、图标
//     */
//    @SuppressWarnings("unused")
//    public static void statusBarDarkMode(Activity activity, int type) {
//        if (type == 1) {
//            MIUISetStatusBarLightMode(activity.getWindow(), false);
//        } else if (type == 2) {
//            flyMeSetStatusBarLightMode(activity.getWindow(), false);
//        } else if (type == 3) {
//            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
//        }
//    }
//
//
//    /**
//     * 设置状态栏图标为深色和魅族特定的文字风格
//     * 可以用来判断是否为Flyme用户
//     *
//     * @param window 需要设置的窗口
//     * @param dark   是否把状态栏文字及图标颜色设置为深色
//     * @return boolean 成功执行返回true
//     */
//    @SuppressWarnings("JavaReflectionMemberAccess")
//    private static boolean flyMeSetStatusBarLightMode(Window window, boolean dark) {
//        boolean result = false;
//        if (window != null) {
//            try {
//                WindowManager.LayoutParams lp = window.getAttributes();
//                Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
//                Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
//                darkFlag.setAccessible(true);
//                meizuFlags.setAccessible(true);
//                int bit = darkFlag.getInt(null);
//                int value = meizuFlags.getInt(lp);
//                if (dark) {
//                    value |= bit;
//                } else {
//                    value &= ~bit;
//                }
//                meizuFlags.setInt(lp, value);
//                window.setAttributes(lp);
//                result = true;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return result;
//    }
//
//    /**
//     * 需要MIUIV6以上
//     *
//     * @param dark 是否把状态栏文字及图标颜色设置为深色
//     * @return boolean 成功执行返回true
//     */
//    @SuppressWarnings({"PrivateApi", "unchecked"})
//    private static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
//        boolean result = false;
//        if (window != null) {
//            Class clazz = window.getClass();
//            try {
//                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
//                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
//                int darkModeFlag = field.getInt(layoutParams);
//                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
//                if (dark) {
//                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
//                } else {
//                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
//                }
//                result = true;
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    //开发版 7.7.13 及以后版本采用了系统API，旧方法无效但不会报错，所以两个方式都要加上
//                    if (dark) {
//                        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                    } else {
//                        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return result;
//    }
//
//    /**
//     * @param activity    当前activity
//     * @param statusColor 颜色值
//     */
//    static void setStatusBarColor(Activity activity, int statusColor) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0以上
//            Window window = activity.getWindow();
//            //取消状态栏透明
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            //添加Flag把状态栏设为可绘制模式
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            //设置状态栏颜色
//            window.setStatusBarColor(statusColor);
//            //设置系统状态栏处于可见状态
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
//            //让view不根据系统窗口来调整自己的布局
//            ViewGroup mContentView = window.findViewById(Window.ID_ANDROID_CONTENT);
//            View mChildView = mContentView.getChildAt(0);
//            if (mChildView != null) {
//                mChildView.setFitsSystemWindows(true);
//                mChildView.requestApplyInsets();
//            }
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4-5.0
//            // 设置状态栏透明
//            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            // 生成一个状态栏大小的矩形
//            View statusView = createStatusView(activity, statusColor);
//            // 添加 statusView 到布局中
//            ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
//            decorView.addView(statusView);
//            // 设置根布局的参数
//            ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
//            rootView.setFitsSystemWindows(true);
//            rootView.setClipToPadding(true);
//        }
//    }
//
//    /**
//     * 生成一个和状态栏大小相同的矩形条 * * @param activity 需要设置的activity *
//     *
//     * @param color 状态栏颜色值 *
//     * @return 状态栏矩形条
//     */
//    private static View createStatusView(Activity activity, int color) {
//        // 获得状态栏高度
//        int statusBarHeight = getStatusBarHeight(activity);
//        // 绘制一个和状态栏一样高的矩形
//        View statusView = new View(activity);
//        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
//        statusView.setLayoutParams(params);
//        statusView.setBackgroundColor(color);
//        return statusView;
//    }
//
//    /*获取状态栏高度*/
//    static int getStatusBarHeight(Context context) {
//        Resources resources = context.getResources();
//        int resourceId = 0;
//        try {
//            resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return resources.getDimensionPixelSize(resourceId);
//    }
//
//    public static void fullScreen(Activity activity) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
//                Window window = activity.getWindow();
//                View decorView = window.getDecorView();
//                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
//                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
//                decorView.setSystemUiVisibility(option);
//                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//                window.setStatusBarColor(Color.TRANSPARENT);
//                //导航栏颜色也可以正常设置
////                window.setNavigationBarColor(Color.TRANSPARENT);
//            } else {
//                Window window = activity.getWindow();
//                WindowManager.LayoutParams attributes = window.getAttributes();
//                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
//                attributes.flags |= flagTranslucentStatus;
//                window.setAttributes(attributes);
//            }
//        }
//    }
//
//    /*全屏透明沉浸状态栏*/
//    static void setTransparentStatusBar(Activity activity) {
//        setTransparentStatusBar(activity, false);
//    }
//
//    static void setTransparentStatusBar(final Activity activity, boolean isLightMode) {
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
//        Window window = activity.getWindow();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_VISIBLE;
//            if (isLightMode) {
//                setStatusBarLightMode(window);
//            } else {
//                window.getDecorView().setSystemUiVisibility(option);
//            }
//            window.setStatusBarColor(Color.TRANSPARENT);
//        } else {
//            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        }
//    }

    static void setStatusBarLightMode(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    /**
     * @param activity 当前activity
     * @param colorId  颜色值
     */
    static void setStatusBarColor(Activity activity, @ColorRes int colorId) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0以上
            Window window = activity.getWindow();
            //取消状态栏透明
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //添加Flag把状态栏设为可绘制模式
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(ContextCompat.getColor(activity, colorId));
            //设置系统状态栏处于可见状态
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            //让view不根据系统窗口来调整自己的布局
            ViewGroup contentView = window.findViewById(Window.ID_ANDROID_CONTENT);
            View childView;
            if (contentView != null && (childView = contentView.getChildAt(0)) != null) {
                childView.setFitsSystemWindows(true);
                childView.requestApplyInsets();
            }
        } else {//4.4-5.0  setContentView之后调用才有效
            applyStatusBarColor(activity, colorId);
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static void applyStatusBarColor(Activity activity, @ColorRes int colorId) {
        Window window = activity.getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        window.setAttributes(attributes);
        ViewGroup decorView = (ViewGroup) window.getDecorView();
        // 生成一个状态栏大小的矩形
        View statusView = decorView.findViewWithTag(TAG_STATUS_BAR);
        if (statusView == null) {
            statusView = createStatusBarView(activity);
            // 添加 statusView 到布局中
            decorView.addView(statusView);
        }
        statusView.setBackgroundResource(colorId);
        // 设置根布局的参数
        ViewGroup contentView = window.findViewById(Window.ID_ANDROID_CONTENT);
        if (contentView != null) {
            ViewGroup childView = (ViewGroup) contentView.getChildAt(0);
            if (childView != null) {
                childView.setFitsSystemWindows(true);
                childView.setClipToPadding(true);
            }
        }
    }

    private static View createStatusBarView(final Context context) {
        View statusBarView = new View(context);
        statusBarView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(context)));
        statusBarView.setTag(TAG_STATUS_BAR);
        return statusBarView;
    }

    /*获取状态栏高度*/
    private static int getStatusBarHeight(Context context) {
        try {
            Resources resources = context.getResources();
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            return resources.getDimensionPixelSize(resourceId);
        } catch (Exception e) {
            return 0;
        }
    }

    static void setStatusViewColor(Context context, View statusView, @ColorRes int colorId) {
        if (statusView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ViewGroup.LayoutParams params = statusView.getLayoutParams();
            params.height = getStatusBarHeight(context);
            if (colorId != 0) {
                statusView.setBackgroundResource(colorId);
            }
        }
    }

    //设置全屏  
    public static void setFullscreen(Activity activity) {
        activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /*取消全屏*/
    public static void clearFullscreen(Activity activity) {
        activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /*全屏透明沉浸状态栏*/
    static void setTransparentStatusBar(final Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else {
                //让contentView延伸到状态栏并且设置状态栏颜色透明
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                window.setAttributes(attributes);
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    static void setTranslucentStatus(Activity activity) {
        Window window = activity.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        View decorView = window.getDecorView();
        //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
        int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        decorView.setSystemUiVisibility(option);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
    }

    /**
     * Subtract the top margin size equals status bar's height for view.
     * 当设置全屏沉浸状态栏时，一般使用此方法将toolbar等设置topMargin为statusHeight
     *
     * @param view The view.
     */
    public static void addMarginTopEqualStatusBarHeight(Context context, @NonNull View view) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        layoutParams.setMargins(layoutParams.leftMargin,
                layoutParams.topMargin + getStatusBarHeight(context),
                layoutParams.rightMargin,
                layoutParams.bottomMargin);
    }

    /*与上述方法效果相反*/
    public static void subtractMarginTopEqualStatusBarHeight(Context context, @NonNull View
            view) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        layoutParams.setMargins(layoutParams.leftMargin,
                layoutParams.topMargin - getStatusBarHeight(context),
                layoutParams.rightMargin,
                layoutParams.bottomMargin);
    }
}
